<template>
  <div class="appointment-table-container">
    <!-- 表格 -->
    <el-table :data="tableData" stripe border style="width: 100%" v-loading="loading" @row-click="handleRowClick">

      <el-table-column prop="room.name" label="房间" width="100" align="center" />
      <el-table-column prop="medicalStaff.name" label="治疗师" width="120" align="center" />
      <el-table-column prop="patient_name" label="姓名" width="80" align="center" />
      <el-table-column prop="start_time" label="开始时间" width="90" align="center">
        <template #default="{ row }">
          {{ formatDateTime(row.start_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="end_time" label="结束时间" width="90" align="center">
        <template #default="{ row }">
          {{ formatDateTime(row.end_time) }}
        </template>
      </el-table-column>
      <el-table-column label="服务项目" width="180" align="left">
        <template #default="{ row }">
          <div v-if="Array.isArray(row.health_items) && row.health_items.length > 0">
            <div v-for="(i, idx) in row.health_items" :key="idx">
              {{ i.name }}（{{ i.duration }}分）
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="id" label="ID" width="80" align="center" /> -->

      <!-- <el-table-column prop="patient_phone" label="患者电话" width="130" align="center" /> -->
      <el-table-column prop="patient_gender" label="性别" width="60" align="center">
        <template #default="{ row }">
          <el-tag :type="row.patient_gender === 1 ? 'primary' : 'danger'" size="small">
            {{ row.patient_gender === 1 ? '男' : '女' }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="patient_age" label="年龄" width="80" align="center" /> -->


      <!-- <el-table-column prop="symptoms" label="症状描述" min-width="200" show-overflow-tooltip /> -->
      <!-- <el-table-column prop="is_cancel" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.is_cancel === 1 ? 'danger' : 'success'" size="small">
            {{ row.is_cancel === 1 ? '已取消' : '正常' }}
          </el-tag>
        </template>
      </el-table-column> -->
      <!-- <el-table-column prop="cancel_reason" label="取消原因" width="150" show-overflow-tooltip /> -->

      <!-- <el-table-column prop="created_at" label="创建时间" width="160" align="center">
        <template #default="{ row }">
          {{ formatDateTime(row.created_at) }}
        </template>
      </el-table-column> -->
      <el-table-column label="操作" width="140" align="center" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain :disabled="!canRelease(row)"
            @click.stop="releaseAppointment(row)">释放</el-button>
          <el-button size="small" type="danger" plain :disabled="!canCancel(row)"
            @click.stop="cancelAppointment(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import createAxios from '/@/utils/axios'

interface AppointmentRecord {
  id: number
  store_id: number
  room_id: number
  room_name?: string
  medical_staff_id: number
  medical_staff_name?: string
  patient_name: string
  patient_phone: string
  patient_gender: number
  patient_age: number
  symptoms: string
  start_time: string
  end_time: string
  is_cancel: number
  cancel_reason: string
  admin_id: number
  created_at: string
  updated_at: string
  external_id: string
  source: string
  health_items?: Array<{ name: string; duration: number }>
}

interface Props {
  selectedDate: string
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'edit-appointment': [appointment: AppointmentRecord]
  'refresh-appointments': []
}>()

const loading = ref(false)
const tableData = ref<AppointmentRecord[]>([])
const pagination = reactive({
  page: 1,
  pageSize: 100,
  total: 0
})

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  return dayjs(dateTime).format('HH:mm')
}


// 是否可释放：未取消且未结束
const canRelease = (row: AppointmentRecord) => {
  return row.is_cancel === 0
}

// 是否可取消：未取消且未结束（后端不允许结束后取消）
const canCancel = (row: AppointmentRecord) => {
  return row.is_cancel === 0
}

// 获取预约记录数据
const fetchAppointmentRecords = async () => {
  loading.value = true
  try {
    const startTime = dayjs(props.selectedDate).format('YYYY-MM-DD 00:00:00')
    const endTime = dayjs(props.selectedDate).format('YYYY-MM-DD 23:59:59')

    const params = {
      page: pagination.page.toString(),
      pageSize: pagination.pageSize,
      'search[0][field]': 'start_time',
      'search[0][val]': startTime,
      'search[0][operator]': 'egt',
      'search[0][render]': 'datetime',
      'search[1][field]': 'end_time',
      'search[1][val]': endTime,
      'search[1][operator]': 'elt',
      'search[1][render]': 'datetime',
      'search[2][field]': 'is_cancel',
      'search[2][val]': 0,
      'search[2][operator]': 'eq',
      'order': 'start_time,asc',
    }

    // 手动构建查询参数字符串，避免URLSearchParams的转义
    const queryItems = []
    for (const [key, value] of Object.entries(params)) {
      // 将时间值中的空格替换为+号
      const encodedValue = String(value).replace(/ /g, '+')
      queryItems.push(`${key}=${encodedValue}`)
    }
    const queryString = queryItems.join('&')

    const result = await createAxios({
      url: `/admin/Appointment/index?${queryString}`,
      method: 'GET'
    })

    if (result.code === 1) {
      tableData.value = result.data.list || []
      pagination.total = result.data.total || 0
    } else {
      ElMessage.error(result.msg || '获取数据失败')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取预约记录失败:', error)
    ElMessage.error('获取预约记录失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 处理行点击事件
const handleRowClick = (row: AppointmentRecord) => {
  emit('edit-appointment', row)
}

// 处理页面大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchAppointmentRecords()
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchAppointmentRecords()
}

// 监听选中日期变化
watch(() => props.selectedDate, () => {
  pagination.page = 1
  fetchAppointmentRecords()
})

// 暴露刷新方法给父组件
defineExpose({
  refresh: fetchAppointmentRecords
})

// 释放预约：将结束时间设置为当前时间
const releaseAppointment = async (row: AppointmentRecord) => {
  try {
    await ElMessageBox.confirm('确定释放该预约？将结束时间设置为当前时间。', '提示', {
      type: 'warning'
    })

    const now = dayjs().format('YYYY-MM-DD HH:mm:ss')
    const result = await createAxios({
      url: '/admin/Appointment/release',
      method: 'POST',
      data: {
        id: row.id,
      }
    })

    if (result.code === 1) {
      ElMessage.success('释放成功')
      await fetchAppointmentRecords()
      emit('refresh-appointments')
    } else {
      ElMessage.error(result.msg || '释放失败')
    }
  } catch (e) {
    if (String(e).includes('cancel')) return
    ElMessage.error('操作失败')
  }
}

// 删除（取消预约）
const cancelAppointment = async (row: AppointmentRecord) => {
  try {
    await ElMessageBox.confirm('确定取消该预约？', '提示', { type: 'warning' })

    const result = await createAxios({
      url: '/admin/Appointment/cancel',
      method: 'POST',
      data: {
        id: row.id,
        cancel_reason: ''
      }
    })

    if (result.code === 1) {
      ElMessage.success('取消成功')
      await fetchAppointmentRecords()
      emit('refresh-appointments')
    } else {
      ElMessage.error(result.msg || '取消失败')
    }
  } catch (e) {
    if (String(e).includes('cancel')) return
    ElMessage.error('操作失败')
  }
}
</script>

<style scoped lang="scss">
.appointment-table-container {
  background: #ffffff;
  border-radius: 8px;
  padding: 1px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

  :deep(.el-table) {
    .el-table__header {
      background-color: #f8f9fa;

      th {
        background-color: #f8f9fa !important;
        color: #495057;
        font-weight: 600;
      }
    }

    .el-table__row {
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }

  :deep(.el-pagination) {
    .el-pagination__total {
      color: #606266;
    }
  }
}
</style>